/*
 * @Author: your name
 * @Date: 2022-04-14 16:50:54
 * @LastEditTime: 2022-04-20 09:32:46
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \mallAdmin\src\app\main\used-store\out-store\out-sale-info\out-sale-info.component.ts
 */
import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Router, ActivatedRoute } from '@angular/router';

import { CommonService } from '../../../../services-common/common.service';
import { UsedStoreZservice } from '../../used-store-zservice';

@Component({
  selector: 'app-out-sale-info',
  templateUrl: './out-sale-info.component.html',
  styleUrls: ['./out-sale-info.component.scss']
})
export class OutSaleInfoComponent implements OnInit {

  routeParams:any = {}
  formLabelWidth = '100px';

  // 基础信息
  basicInfos: any = {};

  // 出库类型
  outTypeOptions: any = [];
  // 供应商
  supplierOptions: any = [];

  // submit forms
  subForms: any = {
    state: '', // 状态
    supId: '', // 供应商
    consignee: '', // 收货人
    tel: '', // 联系方式
    districtId: '', // 地区ID
    address: '', // 详细地址
    sumPrice: '', // 销售总价
  };
  // 出库明细Table
  warehouseTable: any = [];

  // 状态 1草稿 2待审核 3待打包 4待出库 5已出库 6已签收 7已取消 8审核不通过 9物流异常
  statusOptions: any = {
    1: '草稿',
    2: '待审核',
    3: '待打包',
    4: '待出库',
    5: '已出库',
    6: '已签收',
    7: '已取消',
    8: '审核不通过',
    9: '物流异常'
  }

  constructor(
    private message: NzMessageService,
    private modal: NzModalService,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private services: UsedStoreZservice
  ) { 
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.dictData();
    this.queryDetailData();
  }

  async dictData() {
    this.outTypeOptions = await this.commonService.getDictList('machine_inbound_type');
  }

  // 供应商
  async querySupplierOptions() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.services.querySupplierList(params);
    
    if (res.code === 0) {
      const { records } = res.data || {};
      this.supplierOptions = records.filter((item: any) => item.name);
    } else {
      this.message.error(res.message);
    }
  }

  async queryDetailData() {
    await this.querySupplierOptions();
    let params = {
      id: this.routeParams.id
    }
    const loadId = this.message.loading('数据加载中...', { nzDuration: 0 }).messageId;
    const res: any = await this.services.queryOutStoreDetail(params);
    this.message.remove(loadId);
    
    if (res.code === 0) {
      const { delivery, list } = res.data || {};
      this.basicInfos = delivery || {};
      this.warehouseTable = list || [];

      for (let key in this.subForms) {
        this.subForms[key] = delivery[key] || '';
      }
    } else {
      this.message.error(res.message);
    }
  }

  submitData() {
    if (!this.verifData()) {
      return
    }
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '该信息无法再次修改，确认保存吗？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.submitInterface();
      },
      nzCancelText: '取消'
    });
  }

  async submitInterface() {
    let params = {
      recycleDelivery: {
        ...this.subForms,
        id: this.routeParams.id
      },
      list: this.warehouseTable
    }
    
    const res: any = await this.services.updateOutOrderDetail(params);
    if (res.code === 0) {
      this.message.success('保存成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  regionChange(val: any) {
    this.subForms.districtId = val.valueArrs.length ? val.valueArrs[val.valueArrs.length - 1] : '';
  }

  back() {
    history.back();
  }

  copy(str: any) {
    this.commonService.copyStr(str);
  }

  dictFilter(arr: Array<any>, val: any) {
    let tempObj: any = arr.find((item: any) => item.content == val);
    return tempObj?.name || '-';
  }

  sumTotal(key: string) {
    let sum = 0;
    sum = this.warehouseTable.reduce((total: number, item: any) => {
      return total + (key === 'realValuation' ? ((item[key] || 0) + (item['aprc'] || 0) + (item['cprc'] || 0)) : (item[key] || 0));
    }, 0);
    return sum;
  }

  verifData() {
    if (!this.subForms.sumPrice) {
      this.message.warning('请先输入销售总价');
      return false;
    } else if (this.sumTotal('price') > this.subForms.sumPrice) {
      this.message.warning('[明细单价合计] 超过了 [销售总价]，请检查');
      return false;
    } else {
      return true;
    }
  }

  statusFilter(val: any) {
    return val ? this.statusOptions[val] : '-';
  }
}
